<template>
  <div style="width: 100%">
    <div id="preloader" class="preloader">
      <div class="inner">
        <div class="line1"></div>
        <div class="line2"></div>
        <div class="line3"></div>
      </div>
    </div>
    <section class="fxt-template-animation fxt-template-layout34">
      <div class="fxt-shape">
        <div class="fxt-transformX-L-50 fxt-transition-delay-1">
          <img src="https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/login/login_left.png" style="height: 100vh; z-index: -2; position: relative;" />
        </div>
      </div>
      <div class="container">
        <div class="row">
          <div class="col-lg-7">
            <div class="fxt-column-wrap justify-content-between">
              <div class="fxt-animated-img">
                <div class="fxt-transformX-L-50 fxt-transition-delay-10">
                  <img
                    src="https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/login/login_jyl_o.png"
                    style="width: 763px; height: 725px; margin-top: 200px"
                  />
                </div>
              </div>
              <!-- <div class="fxt-transformX-L-50 fxt-transition-delay-3">
                      <a href="javascript:void(0)" class="fxt-logo"><img src="" alt="Logo"></a>
                  </div>
                  <div class="fxt-transformX-L-50 fxt-transition-delay-5">
                      <div class="fxt-middle-content">
                          <h1 class="fxt-main-title">Sign In to Rechage Direct</h1>
                          <div class="fxt-switcher-description1">If you don’t have an account You can<a href="javascript:void(0)" class="fxt-switcher-text ms-2">Sign Up</a></div>
                      </div>
                  </div>
                  <div class="fxt-transformX-L-50 fxt-transition-delay-7">
                      <div class="fxt-qr-code">
                          <img src="" alt="QR">
                      </div>
                  </div> -->
            </div>
          </div>
          <div class="col-lg-5">
            <div class="fxt-column-wrap justify-content-center">
              <div class="box">
                <div class="_container">
                  <div class="Media Media--alignCenter" style="width: 100%">
                    <div class="Media-body">
                      <div class="Grid">
                        <div class="form">
                          <div
                            class="Media Media--center Media--justifyCenter"
                            style="margin-bottom: 65px"
                          >
                            <img
                              v-if="type === 'login'"
                              width="227px"
                              height="164px"
                              src="https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/login/login_jyl.png"
                              alt=""
                            />
                          </div>
                          <el-form
                            v-if="type === 'login'"
                            ref="ref"
                            class="login-form"
                            :model="model"
                            :rules="rules"
                            novalidate
                          >
                            <div class="inputBx">
                              <el-form-item prop="username">
                                <img
                                  style="width: 32px; position: absolute; left: 8px"
                                  src="https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/login/accounts_jyl.png"
                                  alt=""
                                />
                                <input
                                  type="text"
                                  v-model="model.username"
                                  @input="$refs['ref'].validate()"
                                  placeholder="请输入账号"
                                  required="required"
                                />
                              </el-form-item>
                            </div>
                            <div class="inputBx password">
                              <el-form-item prop="password">
                                <img
                                  style="width: 32px; position: absolute; left: 8px"
                                  src="https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/login/password_jyl.png"
                                  alt=""
                                />
                                <input
                                  id="password-input"
                                  type="password"
                                  v-model="model.password"
                                  @input="$refs['ref'].validate()"
                                  placeholder="请输入密码"
                                  required="required"
                                />
                              </el-form-item>
                            </div>
                            <div>
                              <el-button
                                :loading="loading"
                                type="primary"
                                class="login-bottom"
                                @click.prevent="handleLogin"
                                style="
                                  width: 100%;
                                  font-size: 20px;
                                  border: none;
                                  height: 60px;
                                  background: #005266;
                                  border-radius: 10px;
                                  margin-top: 50px;
                                "
                              >
                                {{ $t('login.login') }}
                              </el-button>
                            </div>
                          </el-form>
                          <el-form
                            v-if="type === 'register'"
                            ref="registerRef"
                            class="login-form"
                            :model="registerModel"
                            :rules="registerRules"
                            novalidate
                          >
                            <div class="inputBx">
                              <el-form-item prop="user_id">
                                <select
                                  v-model="registerModel.user_id"
                                  style="
                                    -webkit-appearance: none;
                                    -moz-appearance: none;
                                    appearance: none;
                                    background-color: #eeeeee;
                                    width: 100%;
                                    outline: none;
                                    border: none;
                                    padding: 8px 10px;
                                    border-radius: 4px;
                                    color: #222222;
                                    font-size: 14px;
                                    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
                                  "
                                  @change="$refs['registerRef'].validate()"
                                >
                                  <option value="" disabled selected>请选择组长</option>
                                  <option
                                    v-for="(item, index) in UserApplyGroup"
                                    :key="index"
                                    :value="item.user_id"
                                  >
                                    {{ item.real_name }}
                                  </option>
                                </select>
                              </el-form-item>
                            </div>
                            <div class="inputBx">
                              <el-form-item prop="real_name">
                                <input
                                  type="text"
                                  v-model="registerModel.real_name"
                                  @input="$refs['registerRef'].validate()"
                                  placeholder="请输入真实姓名"
                                  required="required"
                                />
                              </el-form-item>
                            </div>
                            <div class="inputBx">
                              <el-form-item prop="phone">
                                <input
                                  type="text"
                                  v-model="registerModel.phone"
                                  placeholder="请输入手机号"
                                  @input="$refs['registerRef'].validate()"
                                  maxlength="11"
                                  required="required"
                                />
                              </el-form-item>
                            </div>
                            <div class="inputBx">
                              <el-form-item prop="nickname">
                                <input
                                  type="text"
                                  v-model="registerModel.nickname"
                                  @input="$refs['registerRef'].validate()"
                                  placeholder="请输入IP昵称"
                                  required="required"
                                />
                              </el-form-item>
                            </div>
                            <div class="inputBx">
                              <el-form-item prop="username">
                                <input
                                  type="text"
                                  v-model="registerModel.username"
                                  @input="$refs['registerRef'].validate()"
                                  placeholder="请输入登录账号(至少6位)"
                                  required="required"
                                />
                              </el-form-item>
                            </div>
                            <div class="inputBx password">
                              <el-form-item prop="password">
                                <input
                                  id="password-input"
                                  type="password"
                                  v-model="registerModel.password"
                                  @input="$refs['registerRef'].validate()"
                                  placeholder="请输入密码"
                                  required="required"
                                />
                              </el-form-item>
                            </div>
                            <div class="inputBx password">
                              <el-form-item prop="checkPassword">
                                <input
                                  id="password-input"
                                  type="password"
                                  v-model="registerModel.checkPassword"
                                  @input="$refs['registerRef'].validate()"
                                  placeholder="请输入确认密码"
                                  required="required"
                                />
                              </el-form-item>
                            </div>
                            <div>
                              <el-button
                                :loading="loading"
                                type="primary"
                                class="login-bottom"
                                @click.prevent="handleRegister"
                                style="
                                  width: 240px;
                                  height: 35px;
                                  font-size: 16px;
                                  border: none;
                                  background: #52b36d;
                                  border-radius: 20px;
                                "
                              >
                                提交审核
                              </el-button>
                            </div>
                          </el-form>
                          <!-- <div
                  v-if="type === 'login'"
                  class="Grid Grid--justifyCenter text-sm"
                  style="width: 240px"
                >
                  <text
                    style="
                      cursor: pointer;
                      padding: 20px 0px;
                      font-family: PingFangSC, PingFang SC;
                      font-weight: 400;
                      font-size: 16px;
                      color: #52b36d;
                    "
                    @click="clickRegister"
                  >
                    账号申请
                  </text>
                </div> -->
                        </div>
                      </div>
                      <div
                        v-if="type === 'register'"
                        class="Grid Grid--justifyCenter text-sm"
                        style="width: 274px"
                      >
                        <text
                          style="
                            cursor: pointer;
                            padding: 20px 0px;
                            font-family: PingFangSC, PingFang SC;
                            font-weight: 400;
                            font-size: 16px;
                            margin-left: 34px;
                            color: #52b36d;
                          "
                          @click="
                            () => {
                              type = 'login'
                            }
                          "
                        >
                          返回登录
                        </text>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- box end -->
            </div>
          </div>
        </div>
      </div>
      <div class="fxt-shape-2">
        <div class="fxt-transformX-R-50 fxt-transition-delay-1">
          <img src="https://liaoma-test.oss-cn-shenzhen.aliyuncs.com/liaoma/admin/assets/images/login/login_right.png" style="height: 100vh; z-index: -2; position: relative;" />
        </div>
      </div>
    </section>
    <div
      style="
        position: absolute;
        bottom: 20px;
        left: 0;
        text-align: center;
        color: #999999;
        width: 100%;
        z-index: 2;
        font-size: 14px;
      "
    >
      <a class="text-sm" style="cursor: pointer" href="https://beian.miit.gov.cn" target="_blank"
        >巨有料 All rights reserved. {{ version }} 粤ICP备2023134200号</a
      >
    </div>
  </div>
</template>

<script>
import defaultSettings from '@/settings'
import AjCaptcha from '@/components/AjCaptcha/index.vue'
import { captcha, setting, userApplyAdd, UserApplyGroupList } from '@/api/system/login'
import { useAppStoreHook } from '@/store/modules/app'
import { useSettingsStoreHook } from '@/store/modules/settings'
import { useUserStoreHook } from '@/store/modules/user'
import { delNotice } from '@/utils/settings'

export default {
  name: 'SystemLogin',
  components: { AjCaptcha },
  data() {
    return {
      version: '',
      isBaidu: false,
      name: '登录',
      loading: false,
      redirect: undefined,
      otherQuery: {},
      captcha_switch: 0,
      captcha_mode: 1,
      captcha_type: 'blockPuzzle',
      captcha_src: '',
      login_bg_url: '',
      login_bg_color: '',
      logo_url: '',
      system_name: '新料码',
      model: {
        username: '',
        password: '',
        captcha_id: '',
        captcha_code: '',
        ajcaptcha: {}
      },
      registerModel: {
        user_id: '',
        real_name: '',
        phone: '',
        nickname: '',
        username: '',
        password: '',
        checkPassword: ''
      },
      type: 'login', // register progress
      UserApplyGroup: [],
      logos: []
    }
  },
  computed: {
    captchaHeight() {
      const appStore = useAppStoreHook()
      if (appStore.size == 'large') {
        return '40px'
      } else if (appStore.size == 'small') {
        return '24px'
      }
      return '32px'
    },
    rules() {
      return {
        username: [
          { required: true, message: this.$t('login.Please enter username'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('login.Please enter password'), trigger: 'blur' }
        ],
        captcha_code: [
          { required: true, message: this.$t('login.Please enter captcha code'), trigger: 'blur' }
        ]
      }
    },
    registerRules() {
      return {
        user_id: [{ required: true, message: '请选择组长', trigger: 'blur' }],
        real_name: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
        phone: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => this.validatePhone(rule, value, callback)
          }
        ],
        nickname: [{ required: true, message: 'IP昵称不能为空', trigger: 'blur' }],
        username: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => this.validateUserName(rule, value, callback)
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        checkPassword: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => this.validatePass(rule, value, callback)
          }
        ]
      }
    }
  },
  watch: {
    $route: {
      handler(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    const userAgent = navigator.userAgent
    this.isBaidu = /Baidu/.test(userAgent)
    this.setting()
    document.addEventListener('keyup', this.handleKeydown)
  },
  mounted() {
    ;(function ($) {
      'use strict'

      /*-------------------------------------
      Background image
      -------------------------------------*/
      $('[data-bg-image]').each(function () {
        var img = $(this).data('bg-image')
        $(this).css({
          backgroundImage: 'url(' + img + ')'
        })
      })

      /*-------------------------------------
      After Load All Content Add a Class
      -------------------------------------*/
      window.onload = addNewClass()

      function addNewClass() {
        $('.fxt-template-animation')
          .imagesLoaded()
          .done(function (instance) {
            $('.fxt-template-animation').addClass('loaded')
          })
      }

      /*-------------------------------------
      Toggle Class
      -------------------------------------*/
      $('.toggle-password').on('click', function () {
        $(this).toggleClass('fa-eye fa-eye-slash')
        var input = $($(this).attr('toggle'))
        if (input.attr('type') == 'password') {
          input.attr('type', 'text')
        } else {
          input.attr('type', 'password')
        }
      })

      /*-------------------------------------
      Youtube Video
      -------------------------------------*/
      if ($.fn.YTPlayer !== undefined && $('#fxtVideo').length) {
        $('#fxtVideo').YTPlayer({ useOnMobile: true })
      }

      /*-------------------------------------
      Vegas Slider
      -------------------------------------*/
      if ($.fn.vegas !== undefined && $('#vegas-slide').length) {
        var target_slider = $('#vegas-slide'),
          vegas_options = target_slider.data('vegas-options')
        if (typeof vegas_options === 'object') {
          target_slider.vegas(vegas_options)
        }
      }

      /*-------------------------------------
      OTP Form (Focusing on next input)
      -------------------------------------*/
      $('#otp-form .otp-input').keyup(function () {
        if (this.value.length == this.maxLength) {
          $(this).next('.otp-input').focus()
        }
      })

      /*-------------------------------------
      Social Animation
      -------------------------------------*/
      $('#fxt-login-option >ul >li').hover(function () {
        $('#fxt-login-option >ul >li').removeClass('active')
        $(this).addClass('active')
      })

      /*-------------------------------------
      Preloader
      -------------------------------------*/
      $('#preloader').fadeOut('slow', function () {
        $(this).remove()
      })
    })(jQuery)
  },
  beforeUnmount() {
    document.removeEventListener('keyup', this.handleKeydown)
  },
  methods: {
    validatePhone(rule, value, callback) {
      if (/^1([3589]\d|4[5-9]|6[1-2,4-7]|7[0-8])\d{8}$/.test(value)) {
        callback()
      } else {
        callback(new Error('手机号格式有误'))
      }
    },
    validatePass(rule, value, callback) {
      if (this.registerModel.password && value !== this.registerModel.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    },
    validateUserName(rule, value, callback) {
      if (/^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/.test(value)) {
        callback()
      } else {
        callback(new Error('请以字母开头，至少6位'))
      }
    },
    // 验证码
    captcha() {
      captcha().then((res) => {
        this.captchaData(res.data)
      })
    },
    captchaData(data) {
      this.model.captcha_id = ''
      this.model.captcha_code = ''
      if (data.captcha_switch) {
        if (data.captcha_mode === 1) {
          this.captcha_src = data.captcha_src
          this.model.captcha_id = data.captcha_id
        }
      }
      this.captcha_switch = data.captcha_switch
      this.captcha_mode = data.captcha_mode
      if (data.captcha_type === 1) {
        this.captcha_type = 'blockPuzzle'
      } else {
        this.captcha_type = 'clickWord'
      }
      const storePrefix = defaultSettings.storePrefix
      localStorage.setItem(storePrefix + 'captchaSwitch', data.captcha_switch)
      localStorage.setItem(storePrefix + 'captchaMode', data.captcha_mode)
      localStorage.setItem(storePrefix + 'captchaType', data.captcha_type)
      localStorage.setItem(storePrefix + 'captchaSrc', data.captcha_src)
    },
    ajcaptchaSuccess(params) {
      this.model.ajcaptcha = params
      this.handleLogin()
    },
    ajcaptchaShow() {
      this.$refs['ref'].validate((valid) => {
        if (valid) {
          this.$refs.ajcaptcha.show()
        } else {
          return false
        }
      })
    },
    // 设置
    setting() {
      const storePrefix = defaultSettings.storePrefix
      this.login_bg_url = localStorage.getItem(storePrefix + 'loginBgUrl')
      this.login_bg_color = localStorage.getItem(storePrefix + 'loginBgColor')
      this.logo_url = localStorage.getItem(storePrefix + 'logoUrl')
      this.system_name = localStorage.getItem(storePrefix + 'systemName')
      this.model.captcha_id = ''
      this.model.captcha_code = ''
      this.captcha_switch = localStorage.getItem(storePrefix + 'captchaSwitch')
      this.captcha_mode = localStorage.getItem(storePrefix + 'captchaMode')
      this.captcha_type = localStorage.getItem(storePrefix + 'captchaType')
      this.captcha_src = localStorage.getItem(storePrefix + 'captchaSrc')
      const settingsStore = useSettingsStoreHook()
      settingsStore.changeSetting({ key: 'watermarkContent', value: '' })
      setting()
        .then((res) => {
          delNotice()
          const data = res.data
          this.captchaData(data)
          this.login_bg_url = data.login_bg_url
          this.login_bg_color = data.login_bg_color
          this.logo_url = data.logo_url
          this.system_name = data.system_name
          this.version = data.version
          this.logos = data.logos
          settingsStore.changeSetting({ key: 'loginBgUrl', value: data.login_bg_url })
          settingsStore.changeSetting({ key: 'loginBgColor', value: data.login_bg_color })
          settingsStore.changeSetting({ key: 'logoUrl', value: data.logo_url })
          settingsStore.changeSetting({ key: 'systemName', value: data.system_name })
          settingsStore.changeSetting({ key: 'pageTitle', value: data.page_title })
          settingsStore.changeSetting({ key: 'pageLimit', value: data.page_limit })
          settingsStore.changeSetting({ key: 'notice', value: 0 })
          settingsStore.changeSetting({ key: 'watermarkEnabled', value: data.is_watermark })
        })
        .catch(() => {})
    },
    // 登录
    handleLogin() {
      this.$refs['ref'].validate((valid) => {
        if (valid) {
          this.loading = true
          const userStore = useUserStoreHook()
          userStore
            .login(this.model)
            .then(() => {
              this.$router
                .push({
                  path: this.redirect || '/',
                  query: this.otherQuery
                })
                .catch(() => {
                  this.loading = false
                })
            })
            .catch(() => {
              this.loading = false
              if (this.captcha_switch && this.captcha_mode === 2) {
                this.$refs.ajcaptcha.refresh()
              } else {
                this.captcha()
              }
            })
        } else {
          return false
        }
      })
    },
    // 账号申请
    handleRegister() {
      this.$refs['registerRef'].validate((valid) => {
        if (valid) {
          this.loading = true
          userApplyAdd(this.registerModel)
            .then((res) => {
              this.loading = false
              if (res.code === 200) {
                this.registerModel = {
                  user_id: '',
                  real_name: '',
                  phone: '',
                  nickname: '',
                  username: '',
                  password: '',
                  checkPassword: ''
                }
                ElMessage({
                  message: '账号申请成功，请等待管理员审核!',
                  type: 'success',
                  duration: 3000,
                  customClass: 'hintMessage'
                })
              } else {
                ElMessage.error('账号申请失败!')
              }
            })
            .catch(() => {
              this.loading = false
              ElMessage.error('账号申请失败!')
            })
        } else {
          return false
        }
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    handleKeydown(e) {
      if (e.keyCode === 13) {
        this.handleLogin()
      }
    },
    clickRegister() {
      // 获取组长
      UserApplyGroupList()
        .then((res) => {
          console.log(res)
          if (res.code === 200) {
            this.UserApplyGroup = res.data.list
          }
        })
        .catch(() => {})
      this.type = 'register'
    }
  }
}
</script>
<style>
.hintMessage {
  top: 50% !important;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
<style lang="scss" scoped>
@import '@/styles/login/style.css';

section {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #f7f7f7 !important;
  animation: gradient 10s ease infinite;
  overflow: hidden;
}

.box {
  position: relative;
  z-index: 2;
}

._container {
  position: relative;
  width: 629px;
  min-height: 794px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 1);
  padding: 0 105px;
}

._container::after {
  content: '';
  position: absolute;
  top: 5px;
  right: 5px;
  bottom: 5px;
  left: 5px;
  border-radius: 5px;
  pointer-events: none;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.1) 2%);
}

.form {
  position: relative;
  height: auto;
  width: 100%;

  h2 {
    color: #fff;
    letter-spacing: 2px;
  }

  .inputBx {
    position: relative;
    width: 100%;
    margin-bottom: 25px;

    input {
      width: 100%;
      outline: none;
      border: none;
      // padding: 8px 10px;
      padding: 0 10px 0 50px;
      height: 60px;
      line-height: 60px;
      border-radius: 10px;
      color: #222222;
      font-size: 16px;
      // box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
      background: #ebf6f9;
    }

    input[type='submit'] {
      background: #fff;
      color: #111;
      max-width: 100px;
      padding: 8px 10px;
      box-shadow: none;
      letter-spacing: 1px;
      cursor: pointer;
      transition: 1.5s;
    }

    input[type='submit']:hover {
      background: linear-gradient(115deg, rgba(0, 0, 0, 0.1), rgba(255, 255, 255, 0.25));
      color: #fff;
      transition: 0.5s;
    }

    input::placeholder {
      color: #aeafad;
    }

    span {
      position: absolute;
      left: 30px;
      padding: 7px 10px;
      display: inline-block;
      color: #888888;
      transition: 0.5s;
      pointer-events: none;
    }

    input:focus ~ span,
    input:valid ~ span {
      transform: translateX(-30px) translateY(-25px);
      font-size: 12px;
    }
  }

  p {
    color: #fff;
    font-size: 15px;
    margin-top: 5px;

    a {
      color: #fff;
    }

    a:hover {
      background-color: #000;
      background-image: linear-gradient(to right, #434343 0%, black 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }
}
::v-deep .el-form-item__content {
  .el-form-item__error {
    line-height: 16px;
  }
}
/* 针对纵向手机设备 */
@media (max-width: 768px) and (orientation: portrait) {
  ._container {
    width: 100%;
    padding: 0 10%;
    min-height: 568px;
  }
  .fxt-template-layout34 .fxt-animated-img img {
    width: 350px !important;
    height: auto !important;
    position: relative;
    left: 50%;
    transform: translateX(-30%);
    margin-top: 116px !important;
  }
}

::v-deep .el-select .el-input__inner {
  border: none;
}

video::-webkit-media-controls {
  display: none !important;
}
</style>
